package com.zero.manage.web.config.shiro;

import cn.hutool.json.JSONUtil;
import io.gitee.zerowsh.enums.ResultEnums;
import io.gitee.zerowsh.util.PublicResult;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 没有权限是直接返回json，不适用shiro的跳转方式
 *
 * @author
 */
@Log4j2
public class MyAuthorizationFilter extends PermissionsAuthorizationFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        Subject subject = getSubject(request, response);
        // If the subject isn't identified, redirect to login URL
        if (subject.getPrincipal() == null) {
            saveRequestAndRedirectToLogin(request, response);
        } else {
            resp.setStatus(ResultEnums.UNAUTHORIZED.getKey());
            resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
            resp.setHeader("Access-Control-Allow-Credentials", "true");
            resp.setContentType("application/json; charset=utf-8");
            resp.setCharacterEncoding("UTF-8");
            try (PrintWriter out = resp.getWriter()) {
                out.append(JSONUtil.toJsonStr(PublicResult.resultEnums(ResultEnums.UNAUTHORIZED)));
                out.flush();
            } catch (Exception e) {
                log.error(e);
            }
        }
        return false;
    }
}
